<?php

namespace App\Utility;

use EasySwoole\EasySwoole\Config;

class ApiToken
{
    /**
     * 加解密
     * @param $data
     * @return string
     */
    public static function decryptWithOpenssl($data)
    {
        $config = Config::getInstance()->getConf('token');
        return openssl_decrypt(base64_decode($data),"AES-128-CBC",$config['key'],OPENSSL_RAW_DATA,$config['iv']);
    }

    public static function encryptWithOpenssl($data)
    {
        $config = Config::getInstance()->getConf('token');
        return base64_encode(openssl_encrypt($data,"AES-128-CBC",$config['key'],OPENSSL_RAW_DATA,$config['iv']));
    }


    /**构建会话加密函数，默认30天超时
     * @param $data
     * @param int $expires 过期时间
     * @return string
     */
    public static function sessionEncrypt($data, $expires=2592000)
    {
        $expires = time() + $expires;
        return self::encryptWithOpenssl($data.'|'.$expires);
    }

    /**
     * 验证会话token是否有效
     * @param $raw
     * @return bool
     */
    public static function sessionCheckToken($raw)
    {
        $data = self::decryptWithOpenssl($raw);
        //如果解密不出文本返回失败
        if(!$data){
            return false;
        }
        $token = explode('|', $data);
        //如果分离出来的openid的过期时间为空 返回失败
        if(!isset($token[0]) || !isset($token[1])){
            return false;
        }
        //如果时间过期，返回失败
        if( $token[1] < time()){
            return false;
        }
        return $token[0];
    }
}
